///必定会返回一个默认值
class BaseDefaultsValue {
  BaseDefaultsValue._();

  ///int 类型默认值
  static int intDefaults(dynamic data, {int defaultValue = 0}) {
    if (data == null || data.toString().isEmpty) return defaultValue;
    if (data is String) {
      int parse = int.tryParse(data);
      if (parse != null) return parse;
      return defaultValue;
    }
    if (data is double) return data.toInt();
    if (data is int) return data;
    return defaultValue;
  }

  ///double 类型默认值
  ///toStringAsFixed  <= 0 则不处理小数
  static double doubleDefaults(dynamic data, {double defaultValue = 0.0, int toStringAsFixedFractionDigits = -2}) {
    if (data == null || data.toString().isEmpty) return defaultValue;
    if (data is String) {
      double parse = double.tryParse(data);
      if (parse != null) {
        if (toStringAsFixedFractionDigits > 0) {
          String _toStringAsFixed = parse.toStringAsFixed(toStringAsFixedFractionDigits);
          return double.parse(_toStringAsFixed);
        }
        return parse;
      }
      return defaultValue;
    }
    if (data is int) return data.toDouble();
    if (data is double) {
      if (toStringAsFixedFractionDigits > 0) {
        return double.parse(data.toStringAsFixed(toStringAsFixedFractionDigits));
      }
      return data;
    }
    return defaultValue;
  }

  ///改变价格单位
  ///allowToBeEmpty: 是否允许为空 如果为true,则直接返回
  ///price:  需要转化的价格
  ///unitName:单位名称，如果不传则不将其拼接返回
  ///divisor：除数（比如：万：10000.0,千：1000.0）
  ///decimal:需要保留的小数位，默认是2
  ///isContinue: 如果被除数(price) 小于 除数(divisor)是否继续转化
  ///allowEndsWithZero: 当结尾为.00的时候是否允许.00存在
  static String changeUnit(dynamic price, {bool allowToBeEmpty = false, double divisor = 1, String unitName = "", int decimal = 2, bool isContinue = true, bool allowEndsWithZero = true}) {
    if (allowToBeEmpty && (price == null || price.toString().isEmpty)) return price;
    double priceDouble = doubleDefaults(price);
    if (divisor == null || divisor == 0) divisor = 1;
    if (priceDouble < divisor && !isContinue) {
      if (!allowEndsWithZero) return stringNotAllowEndsWithZero(priceDouble.toStringAsFixed(2));
      return priceDouble.toStringAsFixed(2);
    }
    double changePrice = priceDouble / divisor;
    if (!allowEndsWithZero) return "${stringNotAllowEndsWithZero(changePrice.toStringAsFixed(decimal))}$unitName";
    return "${changePrice.toStringAsFixed(decimal)}$unitName";
  }

  /// 把一个string的字符串转成 （ 百分比 或者 double ）
  /// eg: 0.13564' => 13.56% 转成百分比 最多保留2位小数
  /// eg: '0.13564' => 0.13  转成double 最多保留2位小数
  /// metadata: 元数据
  /// getPercentage：得到百分比
  /// getDouble：取double值
  /// getChangeUnit: 将金额转为w单位
  /// getThousandsSeparator：取千分位分隔符号的值
  /// decimalPlace:需要保留的小数位，默认是2
  static dynamic transformMetadata(dynamic metadata, {bool getPercentage = false, bool getDouble = false, bool getThousandsSeparator = false, bool getChangeUnit = false, int decimalPlace = 2}) {
    if (metadata == null) return metadata;
    if (!(metadata is String) && !(metadata is int) && !(metadata is double) && !(metadata is num)) return metadata;
    if (!getPercentage && !getDouble && !getThousandsSeparator && !getChangeUnit) return metadata;
    if (metadata is int || (metadata is String && int.tryParse(metadata) != null)) {
      int data = metadata is String ? int.tryParse(metadata) : metadata;
      if (getPercentage) return '${stringNotAllowEndsWithZero('${data * 100}')}%';
      if (getDouble) return double.tryParse(stringNotAllowEndsWithZero(data.toDouble().toStringAsFixed(decimalPlace)));
      if (getThousandsSeparator) return thousandsSeparator(data);
      if (getChangeUnit) return changeUnit(metadata, divisor: 10000, unitName: 'w', isContinue: false, decimal: decimalPlace, allowEndsWithZero: false);
    }
    if (metadata is double || (metadata is String && double.tryParse(metadata) != null)) {
      double data = metadata is String ? double.tryParse(metadata) : metadata;
      if (getPercentage) return '${stringNotAllowEndsWithZero((data * 100.0).toStringAsFixed(decimalPlace))}%';
      if (getDouble) return double.tryParse(data.toDouble().toStringAsFixed(decimalPlace));
      if (getThousandsSeparator) {
        data = double.tryParse(stringNotAllowEndsWithZero(data.toStringAsFixed(decimalPlace)));
        return thousandsSeparator(decimalPlace == 0 ? data.toInt() : data, handleDecimals: true);
      }
      if (getChangeUnit) return changeUnit(metadata, divisor: 10000, unitName: 'w', isContinue: false, decimal: decimalPlace, allowEndsWithZero: false);
    }

    return metadata;
  }

  /// 字符串不允许以零结尾
  static String stringNotAllowEndsWithZero(String string) {
    if (string == null || string.isEmpty) return string;
    if (!string.contains('.')) return string;
    List<String> _list = string.split('.');
    if (_list[1] == '00') return "${_list[0]}";
    if (_list[1].endsWith('00')) return "${_list[0]}.${_list[1].replaceFirst('00', '', _list[1].length - 2)}";
    if (_list[1].endsWith('0')) return "${_list[0]}.${_list[1].replaceFirst('0', '', _list[1].length - 1)}";
    return "$string";
  }

  /// 千位分隔符
  static thousandsSeparator(num, {point: 3, String interval = ',', bool handleDecimals = false}) {
    if (num != null) {
      String str = double.parse(num.toString()).toString();
      // 分开截取
      List<String> sub = str.split('.');
      // 处理值
      List val = List.from(sub[0].split(''));
      //处理分割符
      for (int index = 0, i = val.length - 1; i >= 0; index++, i--) {
        // 除以三没有余数、不等于零并且不等于1 就加个逗号
        if (index % 3 == 0 && index != 0) val[i] = val[i] + interval;
      }
      String decimals = '';
      if (handleDecimals && !(num is int)) {
        decimals += '.${sub[1]}';
      }
      return '${val.join('')}$decimals';
    } else {
      return "0";
    }
  }
}
